﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>table组件综合演示 - Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//unpkg.com/layui@2.11.0/dist/css/layui.css" rel="stylesheet">
    <style>
        .navbar {
            display: none;
        }
    </style>

</head>

<body>
    <!-- 查询 -->
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <input type="text" placeholder="请输入患者名称" name="name" class="layui-input">
            </div>
            <div class="layui-input-inline">
                <input type="text" placeholder="请输入日期（格式：YYYY-MM-DD）" name="opTime" id="opTime" class="layui-input">
            </div>
            <button class="layui-btn layui-bg-blue" lay-submit lay-filter="search">查询</button>
            <button type="button" class="layui-btn layui-bg-green" id="exportBtn">导出Excel</button>
            <input type="file" id="importFile" style="display: none;">
            <button type="button" class="layui-btn layui-bg-orange" id="importBtn">导入</button>
        </div>
    </form>
    <!-- 表格 -->
    <table class="layui-hide" id="role-table"></table>
    <script type="text/html" id="toolDemo">
        <div class="layui-clear-space">
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="DetailDoorSpend">⚙</a>
        </div>
    </script>
    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script>
        layui.use(['table', 'jquery', 'layer', 'form', 'laydate'], function () {
            var table = layui.table;
            var $ = layui.jquery;
            var layer = layui.layer;
            var form = layui.form;
            var laydate = layui.laydate;

            // 日期选择器初始化
            laydate.render({
                elem: '#opTime',
                type: 'date'
            });

            // 封装API调用函数
            function getTitleManagementList(PageIndex, PageSize, name, opTime) {
                return new Promise((resolve, reject) => {
                    var params = {
                        PageIndex: PageIndex || 1,
                        PageSize: PageSize || 15,
                        Name: name,
                        OpTime: opTime
                    };

                    $.ajax({
                        //url: 'https://localhost:7171/api/DoorSpend/GetDoorSpend',
                         url: `@ViewBag.BaseUrl/T5/DoorSpend/GetDoorSpend`,
                        data: params,
                        type: 'get',
                        dataType: 'json',
                        success: function (res) {
                            resolve(res);
                        },
                        error: function (xhr, status, error) {
                            reject({ status, error, responseText: xhr.responseText });
                        }
                    });
                });
            }

            // 导出Excel文件
            function exportData() {
                var name = $('[name="name"]').val();
                var opTime = $('#opTime').val();

                // 显示加载中提示
                layer.load(2);

                // 构建查询参数
                var params = {
                    Name: name || '',
                    OpTime: opTime || ''
                };

                // 使用jQuery的param方法将对象转换为查询字符串
                var queryString = $.param(params);
                //var url = 'https://localhost:7171/api/DoorSpend/Export?' + queryString;
                var url = '@ViewBag.BaseUrl/T5/DoorSpend/Export?' + queryString;

                // 使用fetch API进行请求
                fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
               .then(response => {
                    layer.closeAll('loading');

                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }

                    return response.blob();
                })
               .then(blob => {
                    // 创建下载链接
                    var downloadUrl = window.URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.href = downloadUrl;

                    // 设置文件名，使用当前时间戳确保唯一性
                    var fileName = '门诊消费_' + new Date().toISOString().slice(0, 10) + '.xlsx';
                    a.download = fileName;

                    // 触发点击事件下载文件
                    document.body.appendChild(a);
                    a.click();

                    // 清理
                    window.URL.revokeObjectURL(downloadUrl);
                    document.body.removeChild(a);

                    layer.msg('导出成功', { icon: 1 });
                })
               .catch(error => {
                    layer.closeAll('loading');
                    layer.msg('导出失败:'+ error.message, { icon: 2 });
                    console.error('导出错误:', error);
                });
            }

            // 初始化表格
            table.render({
                elem: '#role-table',
                id: 'DoorSpendtable',
                height: 500,
                cols: [[
                    { type: 'checkbox' },
                    { field: 'opTime', title: '操作时间' },
                    { field: 'orderId', title: '订单号' },
                    { field: 'name', title: '患者姓名' },
                    { field: 'patientNo', title: '就诊卡号' },
                    { field: 'businessType', title: '业务类型' },
                    { field:'moneyType', title: '费用类型' },
                    { field: 'payType', title: '支付方式' },
                    { field:'money', title: '支付金额' },
                    { field: 'paymentStatus', title: '缴费状态' },
                    { title: '操作', toolbar: '#toolDemo' }
                ]],
                page: true,
                limit: 15,
                limits: [2, 15, 30, 50]
            });

            function loadRoleData(PageIndex, PageSize) {
                layer.load(2);
                var name = $('[name="name"]').val();
                var opTime = $('#opTime').val();
                getTitleManagementList(PageIndex, PageSize, name, opTime)
                   .then(res => {
                        layer.closeAll('loading');
                        if (res.code === 0) {
                            table.reload('DoorSpendtable', {
                                data: res.data,
                                count: res.totalCount,
                                limit: PageSize || 15,
                                curr: PageIndex || 1
                            });
                        } else {
                            layer.msg('获取数据失败:'+ (res.message || '未知错误'), { icon: 2 });
                        }
                    })
                   .catch(error => {
                        layer.closeAll('loading');
                        layer.msg('请求失败:'+ error.error, { icon: 2 });
                        console.error('Ajax请求失败:', error);
                    });
            }

            // 页面加载完成后获取数据
            loadRoleData(1, 15);

            // 表单提交事件
            form.on('submit(search)', function () {
                loadRoleData();
                return false;
            });

            // 导出按钮点击事件绑定
            $('#exportBtn').click(function (e) {
                e.preventDefault();
                exportData();
            });

            // 导入按钮点击事件
            $('#importBtn').click(function (e) {
                e.preventDefault();
                $('#importFile').click();
            });

            // 文件选择事件
            $('#importFile').change(function () {
                var file = this.files[0];
                if (file) {
                    var formData = new FormData();
                    formData.append('file', file);

                    layer.load(2);

                    $.ajax({
                        //url: 'https://localhost:7027/api/DoorSpend/ImportInventories',
                        url: '@ViewBag.BaseUrl/T6/DoorSpend/ImportInventories',
                        type: 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (res) {
                            layer.closeAll('loading');
                            if (res.code === 100) {
                                layer.msg('导入成功', { icon: 1 });
                                loadRoleData(1, 15);
                            } else {
                                layer.msg('导入失败:'+ (res.message || '未知错误'), { icon: 2 });
                            }
                        },
                        error: function (xhr, status, error) {
                            layer.closeAll('loading');
                            layer.msg('请求失败:'+ error, { icon: 2 });
                            console.error('Ajax请求失败:', error);
                        }
                    });
                }
            });

            // 监听DetailDoorSpend事件
            table.on('tool(DoorSpendtable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'DetailDoorSpend') {
                    // 弹出确认框
                    layer.confirm('你确定要查看该订单的详情吗？', {
                        btn: ['确定', '取消']
                    }, function () {
                        // 构造跳转链接，添加orderId作为参数
                        var url = `/DoorSpend/DetailDoorSpend?orderId=${data.orderId}`;
                        console.log(url);
                        // 页面跳转
                        window.location.href = url;
                    }, function () {
                        layer.msg('操作取消', { icon: 2 });
                    });
                }
            });
        });
    </script>
</body>

</html>    